
import cgi; import cgitb; cgitb.enable()

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from lib import Util, Config, RequestUtil;
from lib import Logger;

class MainPage(webapp.RequestHandler):
	GET_METHOD = 'GET';
	POST_METHOD = 'POST';

	from src.gadgets.servlet import FilesServlet, JsServlet, ProxyServlet, GadgetRenderingServlet, JsonRpcServlet, RestServlet, CertServlet;
	servletMap = {
			Config.get('web_prefix') + '/gadgets/files' : FilesServlet, 
			Config.get('web_prefix') + '/gadgets/js' : JsServlet, 
			Config.get('web_prefix') + '/gadgets/proxy' : ProxyServlet, 
			Config.get('web_prefix') + '/gadgets/makeRequest' : ProxyServlet, 
			Config.get('web_prefix') + '/gadgets/ifr' : GadgetRenderingServlet, 
			Config.get('web_prefix') + '/gadgets/metadata' : JsonRpcServlet, 
			Config.get('web_prefix') + '/social/rest' : RestServlet, 
			Config.get('web_prefix') + '/public.crt' : CertServlet,
			Config.get('web_prefix') + '/public.cer' : CertServlet
			};

	def initializeRequest(self):
		keys = [];
		values = [];

		for k, v in enumerate(self.request.arguments()):
			keys.append(v);
			values.append(self.request.get(v));
# [TODO] : need to remove as we will access it using self by passing it to each and every class
#		RequestUtil.setParams(keys, values, self.request.headers, self);

	def get(self):
		self.processRequest(MainPage.GET_METHOD);

	def post(self):
		self.processRequest(MainPage.POST_METHOD);

	def processRequest(self, method = 'GET'):
		self.initializeRequest();
	
		from src.gadgets.servlet import FilesServlet, JsServlet, ProxyServlet, GadgetRenderingServlet, JsonRpcServlet, RestServlet, CertServlet;

		uri = self.request.path;
		servlet = None;
		
		for url in MainPage.servletMap.keys():			
			if (Util.substr(uri, 0, len(url)) == url):
				# FIXME temporary hack to support both /proxy and /makeRequest with the same event handler
				# makeRequest == /proxy?output=js
				if (url == Config.get('web_prefix') + '/gadgets/makeRequest'):
					import  urllib;
					query = 'output=js';

					for key in self.request.arguments():
						query = query  + '&' + key + '=' + urllib.quote(self.request.get(key));
					
					URL = Config.get('web_prefix') + '/gadgets/proxy?' + query;

					#Logger.quickLog("Redirecting the make '/gadgets/makeRequest' call to URL", Logger.INFO);

					self.redirect(URL);						

				servlet = MainPage.servletMap[url];
				break;
			
		# If we found a correlating servlet, instance and call it. Otherwise give a 404 error
		if (servlet != None):

			#Logger.quickLog(uri + " handled with servlet - " + servlet.__name__);
			caller = servlet(self.request, self.response);

			# Not all clients support the PUT, HEAD & DELETE http methods, they depend on the X-HTTP-Method-Override instead 
		#	if (method == 'POST' && isset(_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
		#		method = _SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
		#	}
			
			try:
				method = method.lower().capitalize();

				if (method == 'Get'):
					#Logger.quickLog('Calling doGet function on class: ' + servlet.__name__);
					caller.doGet();
				elif (method == 'Post'):
					#Logger.quickLog('Calling doPost function on class: ' + servlet.__name__);
					caller.doPost();
				

				else:
					#Logger.quickLog('Invalid method detected: ' + method, Logger.ERROR);
					Util.header(self.response, "HTTP/1.0 405 Method Not Allowed");
					self.response.out.write("<html><body><h1>405 Method Not Allowed</h1></body></html>");
			except:
				#Logger.quickLog('Error while processing gadget: ', Logger.ERROR);
				Util.header(self.response, "HTTP/1.0 405 Method Not Allowed");
				self.response.out.write("<html><body><h1>Error while processing gadget</h1></body></html>");
				
				
		else:
			#Logger.quickLog('No handler found for url: ' + url, Logger.ERROR);
			# Unhandled event, display simple 404 error
			Util.header(self.response, "HTTP/1.0 404 Not Found");
			self.response.out.write("<html><body><h1>404 Not Found</h1></body></html>");




import os;
calledPath = os.environ['PATH_INFO'];

#Logger.quickLog('Page called - ' + calledPath);

webapps = [('/', MainPage)];

found = False;

for url in MainPage.servletMap.keys():
	if(url == calledPath):
		webapps.append((url, MainPage));
		found = True;

#for value in webapps:
#	if (calledPath.lower() == value[0]):
#		found = True;
#		break;

if(not found):
	Logger.quickLog('Not predefined URL: ' + calledPath);
	webapps.append((calledPath, MainPage));
	pass;

#Logger.quickLog('Handler mapping for URLs - ' + ','.join(MainPage.servletMap.keys()));

application = webapp.WSGIApplication(
                                     webapps,
                                     debug=True)


# to stop caching of request, never do this or route your requests to diff .py files
#def main():
#  run_wsgi_app(application)

#if __name__ == "__main__":
  #main()

run_wsgi_app(application)
